package com.authine.cloudpivot.ext.controller;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.authine.cloudpivot.engine.api.facade.BizObjectFacade;
import com.authine.cloudpivot.engine.api.model.bizmodel.BizPropertyModel;
import com.authine.cloudpivot.engine.api.model.bizmodel.BizSchemaModel;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectQueryModel;
import com.authine.cloudpivot.engine.api.model.runtime.SelectionValue;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.PageableImpl;
import com.authine.cloudpivot.engine.component.query.api.helper.Q;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.engine.enums.type.BizPropertyType;
import com.authine.cloudpivot.engine.service.utils.sftp.CustSFTP;
import com.authine.cloudpivot.ext.utils.MyAESUtil;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.exception.PortalException;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

/**
 * @Author hxd
 * @Date 2021/12/14 18:14
 * @Description 中车poc
 **/
@RestController
@RequestMapping("/public/poczc")
@Slf4j
public class PocZcController extends BaseController {


    @Value("${cloudpivot.course.mvToPath:/data/sftp}")
    private String mvToPath;
    @Value("${cloudpivot.course.filePath:/data/temp}")
    private String filePath;

    private String adminId = "2c9280a26706a73a016706a93ccf002b";


    ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(5);


    @GetMapping("createJudges")
    public void createJudges(@RequestParam String bizId) {

        threadPool.schedule(() -> createJudgeObject(bizId), 3, TimeUnit.SECONDS);
    }


    private void createJudgeObject(String bizId) {
        log.info("\n===================进入生成评委评审数据方法,bizId={}", bizId);

        //查询评审分组
        BizObjectCreatedModel psfz = getBizObjectFacade().getBizObject("psfz", bizId);

        if (psfz == null) {
            log.info("生成评委评审数据失败,评审分组数据不存在,bizId={}", bizId);
            return;
        }

//        String fzzt = psfz.getString("fzzt");

//        if ("已分组".equals(fzzt)){
//            log.info("生成评委评审数据失败,评审分组状态为已分组,bizId={}",bizId);
//            return;
//        }

        Map<String, Object> kcsbMap = (Map<String, Object>) psfz.get("kcsb");

        String kcsb = MapUtils.getString(kcsbMap, "id");

        //先查评委评审是否存在
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("pwps");
        queryModel.setQueryCode("pwps");

        queryModel.setPageable(new PageableImpl(0, 20));
        FilterExpression.Item it = Q.it("kcsb", FilterExpression.Op.Eq, kcsb);

        queryModel.setFilterExpr(it);

        Page<BizObjectModel> page = getBizObjectFacade().queryBizObjects(queryModel);
        log.info("\n====================评委评审数据总数:{}", page.getTotal());
        if (page.getTotal() > 0) {
            log.info("\n====================该课程申报评委评审数据已存在:kcsb={}", kcsb);
            return;
        }

        List<SelectionValue> members = (List<SelectionValue>) psfz.getObject("members");

        if (CollectionUtils.isEmpty(members)) {
            log.info("生成评委评审数据失败,评审人员为空,bizId={}", bizId);
            return;
        }

        members.forEach(mb -> createPwps(kcsb, mb.getId()));

        //修改状态
        Map<String, Object> psfzMap = new HashMap<>();
        psfzMap.put("fzzt", "已分组");

        BizObjectCreatedModel bizPsfz = new BizObjectCreatedModel("psfz", psfzMap, false);
        bizPsfz.setId(bizId);

        getBizObjectFacade().saveBizObject(adminId, bizPsfz, false);

        if (log.isDebugEnabled()) {
            log.debug("修改评审状态为已分组");
        }


    }


    private void createPwps(String kcsbId, String userId) {
        if (log.isDebugEnabled()) {
            log.debug("\n=========开始创建评委评审数据,kcsbId={},userId={}", kcsbId, userId);
        }
        Map<String, Object> map = new HashMap<>();

        map.put("kcsb", kcsbId);
        map.put("pwpszt", "未完成");

        BizObjectCreatedModel kcsb = getBizObjectFacade().getBizObject("kcsb", kcsbId);

        if (kcsb != null) {
            map.put("kcbh", kcsb.getString("kcbh"));
        }

        BizObjectCreatedModel pwps = new BizObjectCreatedModel("pwps", map, false);
        pwps.setSequenceStatus(SequenceStatus.DRAFT.name());

        String bizObjectId = getBizObjectFacade().saveBizObject(userId, pwps, false);

        String deptId = null;

        UserModel user = getOrganizationFacade().getUser(userId);
        if (user != null) {
            user.getDepartmentId();
        }
        log.info("\n=======评委评审表单数据创建成功,bizObjectId={}", bizObjectId);

        String instanceId = getWorkflowInstanceFacade().startWorkflowInstance(user.getDepartmentId(), userId, "pwps", bizObjectId, false);
        log.info("\n=======评委评审流程启动成功,instanceId={}", instanceId);

    }

    /**
     * 评分汇总相关逻辑,生成汇总数据
     *
     * @param bizId
     */
    @GetMapping("scoreTotal")
    public void scoreTotal(@RequestParam String bizId) {

        BizObjectCreatedModel pwps = getBizObjectFacade().getBizObject("pwps", bizId);

        if (pwps != null) {
            Map<String, Object> map = (Map<String, Object>) pwps.get("kcsb");
            if (map != null) {
                String id = MapUtils.getString(map, "id");
                if (id != null) {

                    threadPool.schedule(() -> execScoreTotal(id), 3, TimeUnit.SECONDS);
                }
            }
        }


    }


    private void execScoreTotal(String bizId) {
        log.info("\n===========进入评分汇总方法,课程申报id={}", bizId);

        BizObjectFacade bizObjectFacade = getBizObjectFacade();

        //先查评审汇总是否存在
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("pshz");
        queryModel.setQueryCode("pshz");

        queryModel.setPageable(new PageableImpl(0, 20));
        FilterExpression.Item it = Q.it("kcsb", FilterExpression.Op.Eq, bizId);

        queryModel.setFilterExpr(it);

        Page<BizObjectModel> page = bizObjectFacade.queryBizObjects(queryModel);
        log.info("\n====================评审汇总数据存在数量:{}", page.getTotal());
        if (page.getTotal() > 0) {
            log.info("\n====================评审汇总已存在:{}", page.getTotal());
            return;
        }

        //查询评委评审
        queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("pwps");
        queryModel.setQueryCode("pwps");
        queryModel.setPageable(new PageableImpl(0, 100));
        it = Q.it("kcsb", FilterExpression.Op.Eq, bizId);
        queryModel.setFilterExpr(it);
        page = bizObjectFacade.queryBizObjects(queryModel);
        log.info("\n====================评委评审数据存在数量:{}", page.getTotal());
        if (page.getTotal() == 0) {
            log.info("\n====================评委评审数据不存在数量");
            return;
        }
        String kcbh = page.getContent().get(0).getString("kcbh");

        // 评委评审是否通过,全部通过才通过
        // 查找是否存在一个未通过的数据
        boolean status = page.getContent().stream().anyMatch(biz -> !"已完成".equals(biz.getString("pwpszt")));
        log.info("\n====================评委评审数据是否存在未通过的数据:{}", status);
        if (status) {
            String pwpszt = page.getContent().stream().map(biz -> biz.getString("pwpszt")).collect(Collectors.joining(","));
            log.info("\n====================评委评审未全部通过,pwpszt={}", pwpszt);
            return;
        }

        //评分平均值
        Double aver = page.getContent().stream().map(biz -> MapUtils.getDouble(biz.getData(), "total", 0d))
                .collect(Collectors.averagingDouble(Double::doubleValue));


        //创建汇总数据

        Object create = page.getContent().get(0).get("creater");

        log.info("==============获取评审评委创建人:{}", JSON.toJSONString(create));
        List<SelectionValue> clist = (List<SelectionValue>) create;

        UserModel creater = getOrganizationFacade().getUser(clist.get(0).getId());


        MapBuilder<String, Object> mapBuilder = MapBuilder.create(new HashMap<String, Object>())
                .put("kcsb", bizId).put("num", aver).put("rkzt", "未入库").put("kcbh", kcbh);
        BizObjectCreatedModel model = new BizObjectCreatedModel("pshz", mapBuilder.build(), false);
        model.setSequenceStatus(SequenceStatus.COMPLETED.name());
        String hzId = bizObjectFacade.saveBizObject(creater.getId(), model, false);

        log.info("创建汇总数据成功,返回数据id:{}", hzId);

        String instanceId = getWorkflowInstanceFacade().startWorkflowInstance(creater.getDepartmentId(), creater.getId(), "pshz", hzId, true);
        log.info("发起汇总流程成功,instanceId:{}", instanceId);

        //修改评委评审 数据项:评审汇总

        page.getContent().parallelStream().forEach(biz -> {

            BizObjectCreatedModel bizObjectCreatedModel = new BizObjectCreatedModel(biz.getSchemaCode(), new HashMap<>(), false);

            bizObjectCreatedModel.put("pshz", hzId);

            bizObjectCreatedModel.setId(biz.getId());

            bizObjectFacade.saveBizObject(adminId, bizObjectCreatedModel, false);
        });

    }


    /**
     * 进入发布入库方法
     *
     * @param bizId
     */
    @GetMapping("pushStory")
    public ResponseResult pushStory(@RequestParam String bizId) {
        log.info("\n===========进入发布入库方法,评审汇总id={}", bizId);
        ResponseResult.ResponseResultBuilder<Object> resp = ResponseResult.builder().errcode(-1l);
        //获取评审汇总数据
        BizObjectCreatedModel pshz = getBizObjectFacade().getBizObject("pshz", bizId);

        if (pshz == null) {
            return resp.errmsg(StrUtil.format("评审汇总数据不存在,id={}", bizId)).build();
        }

        String sfrk = pshz.getString("sfrk");

        if (!"是".equals(sfrk)) {
            return resp.errmsg("专员未确定是否可以入库,请刷新当前页面").build();
        }
        String rkzt = pshz.getString("rkzt");


        if ("已入库".equals(rkzt)) {
            return resp.errmsg("该课程已入库,请刷新当前页面").build();
        }


        Map<String, Object> kcsbMap = (Map<String, Object>) pshz.get("kcsb");

        //课程申报id
        String kcsbId = MapUtils.getString(kcsbMap, "id");
        //获取课程申报数据
        BizObjectCreatedModel kcsb = getBizObjectFacade().getBizObject("kcsb", kcsbId);

        if (kcsb == null) {
            return resp.errmsg("课程申报数据不存在").build();
        }

        //组合入库数据
        BizSchemaModel bizSchemaModel = this.getAppManagementFacade().getBizSchemaBySchemaCode("kcqd", true);

        //获取数据项code , 不是子表,已发布,不是默认字段
        List<String> fieldList = bizSchemaModel.getProperties().stream()
                .filter(prop -> !prop.getDefaultProperty() && prop.getPropertyType() != BizPropertyType.CHILD_TABLE && prop.getPublished())
                .map(BizPropertyModel::getCode).collect(Collectors.toList());

        //创建入库普通数据
        Map<String, Object> data = new HashMap<>();
        fieldList.forEach(f -> data.put(f, kcsb.get(f)));


        data.put("sbr", kcsb.get("creater"));
        data.put("sbsj", kcsb.getCreatedTime());
        data.put("kczt", "未启用");
        data.put("dzs", 0);
        data.put("xxrc", 0);
        data.put("drsfxr", false);
        data.put("sfydz", false);

        SelectionValue kczkfr = kcsb.getSelectionObject("kczkfr");
        if (kczkfr != null) {
            data.put("kczkfrtxt", kczkfr.getName());
        }


        //创建子表数据,课程结构kcqdCourseStructures,判断题kcqdJudgmentQuestion,选择题kcqdChoiceQuestion

        List<String> subDefaultCodeList = new ArrayList<>(Arrays.asList("id", "parentId", "modifier", "modifiedTime"));
        //课程结构 kcqdCourseStructures
        List<Map<String, Object>> courseStructuresList = (List<Map<String, Object>>) kcsb.getObject("courseStructures");
        if (CollectionUtils.isNotEmpty(courseStructuresList)) {

            courseStructuresList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("kcqdCourseStructures", courseStructuresList);
        }

        //团队成员
        List<Map<String, Object>> kctdcysList = (List<Map<String, Object>>) kcsb.getObject("kctdcys");
        if (CollectionUtils.isNotEmpty(kctdcysList)) {

            kctdcysList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("kctdcyss", kctdcysList);
        }

//        判断题 kcqdJudgmentQuestion
        List<Map<String, Object>> judgmentQuestionList = (List<Map<String, Object>>) kcsb.getObject("judgmentQuestion");
        if (CollectionUtils.isNotEmpty(judgmentQuestionList)) {

            judgmentQuestionList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("kcqdJudgmentQuestion", judgmentQuestionList);
        }

//        选择题 kcqdChoiceQuestion
        List<Map<String, Object>> choiceQuestionList = (List<Map<String, Object>>) kcsb.getObject("choiceQuestion");
        if (CollectionUtils.isNotEmpty(choiceQuestionList)) {

            choiceQuestionList.stream().forEach(map -> {
                //每条子表数据里把默认字段删掉
                subDefaultCodeList.forEach(k -> map.remove(k));
            });
            data.put("kcqdChoiceQuestion", choiceQuestionList);
        }


        BizObjectCreatedModel bizModel = new BizObjectCreatedModel("kcqd", data, false);
        bizModel.setName(MapUtils.getString(kcsbMap, "name", "入库课程清单"));
        bizModel.setSequenceStatus(SequenceStatus.COMPLETED.name());
        String rkId = getBizObjectFacade().saveBizObject(getUserId(), bizModel, false);

        log.info("创建入库表单数据成功,返回id={}", rkId);


        if (rkId != null) {


            //修改评审汇总数据
            pshz.put("rkzt", "已入库");

            getBizObjectFacade().saveBizObject(getUserId(), pshz, false);
            //修改课程申报进度
            Map<String, Object> sbjd = new HashMap<>();
            sbjd.put("sbjdt", 4);
            BizObjectCreatedModel sbjdBiz = new BizObjectCreatedModel("kcsb", sbjd, false);
            sbjdBiz.setId(kcsbId);
            getBizObjectFacade().saveBizObject(getUserId(), sbjdBiz, false);
        }


        return resp.errcode(0l).errmsg("入库成功").build();

    }


    private Lock serialLocal = new ReentrantLock();

    /**
     * 生成课程编码
     *
     * @param
     * @return
     */
    @GetMapping("getKcSequenceNo")
    public void getKcSequenceNo(@RequestParam String bizId) {
        //延时5000 毫秒,精确到毫秒, 如果不通过延时线程去执行,业务规则会出现,模型业务数据未保存,就执行了当前方法
        threadPool.schedule(() -> generateKcSequenceNo(bizId), 3000, TimeUnit.MILLISECONDS);
    }


    /**
     * 生成课程编码
     *
     * @param
     * @return
     */

    private void generateKcSequenceNo(String bizId) {
        log.info("\n===========进入生成课程编码方法,bizId={}", bizId);


        BizObjectCreatedModel kcsb = getBizObjectFacade().getBizObject("kcsb", bizId);

        if (kcsb == null) {
            log.info("\n===========生成课程编码失败,数据不存在,bizId={}", bizId);
            return;
        }

        String kcbh = kcsb.getString("kcbh");

        if (!StringUtils.isEmpty(kcbh)) {
            log.info("\n===========生成课程编码失败,编号已存在,kcbh={},bizId={}", kcbh, bizId);
            return;
        }

        String category = kcsb.getString("category");
        String yearStr = kcsb.getString("year");

        if (StringUtils.isEmpty(category)) {
            log.info("\n===========生成课程编码失败,课程类别为空,bizId={}", bizId);
            return;
        }


        //查询规则
        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("kcbmgz");
        queryModel.setQueryCode("kcbmgz");

        queryModel.setPageable(new PageableImpl(0, 20));
        FilterExpression.Item it = Q.it("category", FilterExpression.Op.Eq, category);

        queryModel.setFilterExpr(it);

        Page<BizObjectModel> page = getBizObjectFacade().queryBizObjects(queryModel);


        if (page.getTotal() == 0) {
            log.info("\n=============课程编码规则未配置");

            return;
        }

        BizObjectModel ruleModel = page.getContent().get(0);

        String code = ruleModel.getString("code");
        int serialSize = MapUtils.getInteger(ruleModel.getData(), "serialSize", 0);
        //QSXY-类别代码-年份-序号编码
        String rule = ruleModel.getString("rule");

        if (StrUtil.isEmpty(yearStr)) {
            yearStr = String.valueOf(LocalDate.now().getYear());
        }

        String ruleCode = rule.replaceAll("类别代码", code).replaceAll("年份", yearStr);

        //查询编码序号
        queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("kcbh");
        queryModel.setQueryCode("kcbh");

        queryModel.setPageable(new PageableImpl(0, 20));
        it = Q.it("code", FilterExpression.Op.Eq, ruleCode);

        queryModel.setFilterExpr(it);

        page = getBizObjectFacade().queryBizObjects(queryModel);


        boolean isLock = false;
        String courseCode = null;
        try {
            isLock = serialLocal.tryLock(3, TimeUnit.SECONDS);
            if (isLock) {

                //保存编码序号
                BizObjectModel bizObjectModel;
                int serialNo;
                if (page.getTotal() == 0) {
                    log.info("==========================新增编码序号");
                    bizObjectModel = new BizObjectCreatedModel("kcbh", new HashMap<String, Object>(), false);
                    bizObjectModel.put("code", ruleCode);
                } else {
                    log.info("==========================修改编码序号");
                    bizObjectModel = page.getContent().get(0);
                }

                serialNo = MapUtils.getInteger(bizObjectModel.getData(), "serialNo", 0);
                serialNo++;
                bizObjectModel.put("serialNo", serialNo);
                //保存
                getBizObjectFacade().saveBizObject(adminId, bizObjectModel, false);

                //序号补0
                String serialNoStr = String.valueOf(serialNo);

                if (serialSize > serialNoStr.length()) {
                    serialNoStr = String.format("%0" + serialSize + "d", serialNo);
                }

                courseCode = ruleCode.replaceAll("序号编码", serialNoStr);

                log.info("\n==============获取到课程编号:{}", courseCode);
            }

        } catch (Exception e) {
            log.info("======================生成课程编号失败,系统异常:{}", e);
            return;
        } finally {
            if (isLock) {
                serialLocal.unlock();
            }
        }

        if (courseCode != null) {
            kcsb.put("kcbh", courseCode);
            getBizObjectFacade().saveBizObject(kcsb.getCreater().getId(), kcsb, false);
        }

    }

    private final static ExecutorService singleExecutorService = Executors.newSingleThreadExecutor();

    /**
     * 点击量,下载量修改
     *
     * @param bizId
     * @param type
     */
    @GetMapping("courseStatistics")
    public void courseStatistics(@RequestParam String bizId, @RequestParam Integer type) {
        log.info("\n==========进入点击量增加方法:bizId={},type={}", bizId, type);
        if (StringUtils.isEmpty(bizId) || type == null || (type != 1 && type != 2)) {
            return;
        }
        singleExecutorService.execute(() -> incrCourseStatistics(bizId, type));
    }

    /**
     * @param bizId
     * @param type  1 点击量, 2.下载(预览,学习)量
     */
    private void incrCourseStatistics(String bizId, Integer type) {

        BizObjectCreatedModel kcqd = getBizObjectFacade().getBizObject("kcqd", bizId);

        if (kcqd == null) {
            log.info("\n=============点击量记录失败,表单数据不存在,bizId={}", bizId);
            return;
        }
        Map<String, Object> map = new HashMap<>();
        if (type == 1) {
            map.put("djl", MapUtils.getInteger(kcqd.getData(), "djl", 0) + 1);
        } else {
            map.put("xzl", MapUtils.getInteger(kcqd.getData(), "xzl", 0) + 1);
            map.put("xxrc", MapUtils.getInteger(kcqd.getData(), "xxrc", 0) + 1);

        }

        map.put("id", kcqd.getId());

        BizObjectModel bizObjectModel = new BizObjectModel("kcqd", map, false);
        String modifier = adminId;
        if (kcqd.getModifier() != null) {
            modifier = kcqd.getModifier().getId();
        }
        log.info("\n===============点击量和下载量记录:{}", JSON.toJSONString(map));
        getBizObjectFacade().saveBizObject(modifier, bizObjectModel, false);

    }

    /**
     * @param bizId
     * @param type  1 点击量, 2.下载(预览,学习)量
     */
    public void incrCourseStatisticsNew(String bizId, Integer type) {

        BizObjectCreatedModel kcqd = getBizObjectFacade().getBizObject("kcqd", bizId);

        if (kcqd == null) {
            log.info("\n=============点击量记录失败,表单数据不存在,bizId={}", bizId);
            return;
        }
        Map<String, Object> map = new HashMap<>();
        if (type == 1) {
            map.put("djl", MapUtils.getInteger(kcqd.getData(), "djl", 0) + 1);
        } else {
            map.put("xzl", MapUtils.getInteger(kcqd.getData(), "xzl", 0) + 1);
            map.put("xxrc", MapUtils.getInteger(kcqd.getData(), "xxrc", 0) + 1);

        }

        map.put("id", kcqd.getId());

        BizObjectModel bizObjectModel = new BizObjectModel("kcqd", map, false);
        String modifier = adminId;
        if (kcqd.getModifier() != null) {
            modifier = kcqd.getModifier().getId();
        }
        log.info("\n===============点击量和下载量记录:{}", JSON.toJSONString(map));
        getBizObjectFacade().saveBizObject(modifier, bizObjectModel, false);

    }

    /**
     * 加入我的学习操作
     *
     * @param bizId
     */
    public void joinMyStudy(String bizId, String userId) {

        if (StringUtils.isNotEmpty(bizId) && StringUtils.isNotBlank(userId)) {
            boolean isEx = getBizObjectFacade().existsBizObject("kcqd", bizId);
            if (isEx) {

                threadPool.schedule(() -> {

                    BizObjectCreatedModel kcqd = getBizObjectFacade().getBizObject("kcqd", bizId);
                    BizObjectQueryModel queryModel = new BizObjectQueryModel();
                    queryModel.setSchemaCode("myStudy");
                    queryModel.setQueryCode("myStudy");
                    queryModel.setPageable(new PageableImpl(0, 1));
                    FilterExpression.Item it = Q.it("couseIdAndUserId", FilterExpression.Op.Eq, bizId.concat(userId));
                    queryModel.setFilterExpr(it);
                    Page<BizObjectModel> page = getBizObjectFacade().queryBizObjects(queryModel);

                    if (page.getTotal() == 0) {
                        Map<String, Object> data = new HashMap<>();
                        data.put("course", bizId);
                        data.put("courseName", kcqd.getString("courseName"));
                        data.put("couseIdAndUserId", bizId.concat(userId));
                        BizObjectCreatedModel myStudy = new BizObjectCreatedModel("myStudy", data, false);
                        myStudy.setSequenceStatus(SequenceStatus.COMPLETED.name());
                        String id = getBizObjectFacade().saveBizObject(userId, myStudy, false);

                        if (id == null) {
                            log.info("=========加入我的学习保存失败,bizId={}", bizId);
                        }

                    }

                }, 1, TimeUnit.SECONDS);

            } else {
                log.info("=========加入我的学习,课程中心数据不存在,bizId={}", bizId);
            }
        } else {
            log.info("=========加入我的学习失败,bizId={},userId={}", bizId, userId);
        }


    }


    @Autowired
    private CustSFTP custSFTP;

    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("attachmentRelation")
    public ResponseResult attachmentRelation() {
        List<Map<String, Object>> list = new ArrayList<>();
        String redisKey = "courseFileUpload";
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Boolean aBoolean = valueOperations.setIfAbsent(redisKey, "1", 10, TimeUnit.SECONDS);
        if (aBoolean == null || !aBoolean) {
            return getOkResponseResult("正在导入");
        }
        try {
            custSFTP.getRenameInfo(filePath, list);
        } catch (Exception e) {

            e.printStackTrace();
            redisTemplate.delete(redisKey);
            return getErrResponseResult(-1l, "导入失败,系统异常");
        }

        Map<String, List<Map<String, Object>>> fjList = list.stream().collect(Collectors.groupingBy(map -> String.valueOf(map.get("kcbh"))));
        log.info("==============list.size={}", list.size());

        if (fjList.isEmpty()) {
            return getErrResponseResult(-1l, "批量处理文件不存在,目录:".concat(filePath));
        }

        List<Map<String, String>> mvList = new ArrayList<>();

        for (Map.Entry<String, List<Map<String, Object>>> entry : fjList.entrySet()) {
            List<Map<String, String>> mvList1 = addAttachment(entry.getKey(), entry.getValue());
            mvList.addAll(mvList1);
        }

        custSFTP.rename(mvList);
        redisTemplate.delete(redisKey);
        return getOkResponseResult("成功");
    }

    /**
     * 刷新入库清单课程封面
     *
     * @param
     * @return com.authine.cloudpivot.web.api.view.ResponseResult
     * @throws
     */
    @GetMapping("attachmentKCFM")
    public ResponseResult attachmentKCFM() {
        String kcfmPath = "/data/kcfm";
        String stfpPath = "/data/sftp";

        BizObjectFacade bizObjectFacade = getDubboConfigService().getBizObjectFacade();

        List<Map<String, Object>> allKcfmInfo = new ArrayList<>();
        try {
            allKcfmInfo = custSFTP.getAllKcfmInfo(kcfmPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ArrayList<Map<String, String>> mvList = new ArrayList<>();
        for (Map<String, Object> map : allKcfmInfo) {
            BizObjectQueryModel queryModel = new BizObjectQueryModel();
            queryModel.setSchemaCode("kcqd");
            queryModel.setQueryCode("kcqd");
            queryModel.setPageable(new PageableImpl(0, 20));
            String kcbh = (String) map.get("kcbh");
            FilterExpression.Item it = Q.it("kcbh", FilterExpression.Op.Eq, map.get("kcbh"));
            queryModel.setFilterExpr(it);
            Page<BizObjectModel> page = bizObjectFacade.queryBizObjects(queryModel);
            if (page.getContent() == null || page.getContent().size() == 0) {
                log.info("根据课程编号:{}找不到入库清单数据", kcbh);
                continue;
            }
            BizObjectModel rkqd = page.getContent().get(0);
            List<Map<String, Object>> fjList = (List<Map<String, Object>>) rkqd.get("kcfm");

            String refId = (String) map.get("refId");
            log.info("refId==" + refId);
            if (fjList == null) {
                fjList = new ArrayList<Map<String, Object>>();
                Map<String, Object> attMap = new HashMap<>();
                attMap.put("fileSize", map.get("fileSize"));
                attMap.put("mimeType", "image/jpg");
                attMap.put("name", map.get("name"));
                attMap.put("refId", refId);
                fjList.add(attMap);
            } else {
                Map<String, Object> attMap = fjList.get(0);
                attMap.put("fileSize", map.get("fileSize"));
                attMap.put("mimeType", "image/jpg");
                attMap.put("name", map.get("name"));
                attMap.put("refId", refId);
            }
            rkqd.put("kcfm", fjList);
            List<SelectionValue> creater = (List<SelectionValue>) rkqd.get("creater");

            getBizObjectFacade().saveBizObject(getUserId(), rkqd, false);
            //重命名图片
            String name = (String) map.get("name");
            String filePath = kcfmPath + "/" + name;
            String toPath = stfpPath + "/" + refId + name;
            log.info("开始移动图片");

            HashMap<String, String> map1 = new HashMap<>();
            map1.put("filePath", filePath);
            map1.put("toPath", toPath);
            mvList.add(map1);
        }
        custSFTP.rename(mvList);

        return getOkResponseResult("成功");
    }


    private List<Map<String, String>> addAttachment(String kcbh, List<Map<String, Object>> list) {

        BizObjectQueryModel queryModel = new BizObjectQueryModel();
        queryModel.setSchemaCode("kcqd");
        queryModel.setQueryCode("kcqd");

        queryModel.setPageable(new PageableImpl(0, 20));
        FilterExpression.Item it = Q.it("kcbh", FilterExpression.Op.Eq, kcbh);

        queryModel.setFilterExpr(it);

        Page<BizObjectModel> page = getBizObjectFacade().queryBizObjects(queryModel);
        log.info("=====根据kcbh查询数据,page.total={}", page.getTotal());
        if (page.getTotal() == 0) {
            return Lists.newArrayList();
        }

        BizObjectModel bizObjectModel = page.getContent().get(0);


        List<Map<String, String>> mvList = new ArrayList<>();

        String courseName = bizObjectModel.getString("courseName");
        if (StringUtils.isEmpty(courseName)) {
            courseName = kcbh;
        }

        final String filename = courseName;

        list.forEach(map -> {

            Map<String, String> mvMap = new HashMap<>();

            Map<String, Object> m = new HashMap<>();
            String refId = (String) map.get("refId");
            String suffix = (String) map.get("suffix");

            String newFileName = filename.concat(".").concat(suffix);


            m.put("fileSize", map.get("fileSize"));
            m.put("refId", refId);
            m.put("mimeType", map.get("mimeType"));
            m.put("name", newFileName);


            String attachmentCode = "";
            if ("pdf".equals(suffix)) {
                attachmentCode = "jssc";
            } else {
                attachmentCode = "sjfj";
            }
            List<Map<String, Object>> fjList = (List<Map<String, Object>>) bizObjectModel.get(attachmentCode);
            if (fjList == null) {
                fjList = new ArrayList<>();
            }

            fjList.add(m);
            bizObjectModel.put(attachmentCode, fjList);

            mvMap.put("filePath", String.valueOf(map.get("filePath")));
            mvMap.put("toPath", mvToPath.concat("/").concat(refId).concat(newFileName));
            mvList.add(mvMap);
        });

        String s = getBizObjectFacade().saveBizObject(getUserId(), bizObjectModel, false);
        log.info("=============mvList={}", JSON.toJSONString(mvList));
        return mvList;

    }


    @GetMapping("getCode")
    public ResponseResult getCode(String code){

        if (StringUtils.isEmpty(code)) {
            return getErrResponseResult(-1l,"code 不能为空");
        }

        try {
            code =  MyAESUtil.Encrypt(code,"qsyri");
        } catch (Exception e) {
            throw new PortalException(-1l,"加密失败:".concat(e.getMessage()));
        }
        return getOkResponseResult(code,"成功");
    }

}
